//
//  ECMineSafetyViewController.m
//  Edu_iOS2018
//
//  Created by apple on 2018/1/6.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECMineSafetyViewController.h"

#import "ECMineSafeTopStyleCell.h"
#import "ECMineSafeBottomStyleCell.h"

#import "ECMineSafeChangeNameVc.h"
#import "ECMineSafeChangeOrBindTelVc.h"
#import "ECMineSafeCheckPsVc.h"
#import "ECMineSafeChangePasswordVc.h"
#import "ECMineSafeFirstSetPasswordVc.h"

#import <ShareSDK/ShareSDK.h>

@interface ECMineSafetyViewController ()<UITableViewDelegate,UITableViewDataSource>{
    ///密码设置标识
    NSString *strOfStyle;
}

@property (nonatomic, strong) UITableView *safeTBview;
@property (nonatomic, strong) NSMutableArray *dataArray;


@end

@implementation ECMineSafetyViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getDataWithURL];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"账户安全";
    
    strOfStyle = [[NSString alloc]init];
    
    [self.view addSubview:self.safeTBview];
}

-(void)getDataWithURL{
    DLog(@"%@",[[UserInfoManager shareUser] token]);
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HWHttpTool requestWithMethod:@"GET"
                              url:URL_GET_Me
                           params:nil
                          headers:@{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {
                              DLog(@"%@",json);
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              [self.dataArray[0][0] replaceObjectAtIndex:1 withObject:json[@"data"][@"nickname"]];//用户名
                              [self.dataArray[0][1] replaceObjectAtIndex:1 withObject:json[@"data"][@"mobile"]];//绑定手机
                              [self.dataArray[0][2] replaceObjectAtIndex:1 withObject:json[@"data"][@"email"]];//验证邮箱
                              
                              //最后绑定返回标志是:true or false  采用字典形式
                              [self.dataArray[1][0] replaceObjectAtIndex:1 withObject:json[@"data"][@"qqBind"]];//QQ绑定
                              [self.dataArray[1][1] replaceObjectAtIndex:1 withObject:json[@"data"][@"wxBind"]];//微信绑定
                              
                              //根据返回password值(1为已设置过密码,0为未设置过密码)设置cell中 密码的显示状态
                              strOfStyle = ([json[@"data"][@"password"] intValue] == 1) ? @"已设置" : @"未设置";
                                  [self.dataArray[0][3] replaceObjectAtIndex:1 withObject:strOfStyle];
                              
                              [self.safeTBview reloadData];
                          }
                          failure:^(NSError *error) {
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              NSString *str = [ECData_Json requestErrorTipWith:error];
                              DLog(@"%@",str);
                              if (!([str isEqualToString:@"101"] || [str isEqualToString:@"401"])) {
                                  [MBProgressHUD showTipMessageInWindow:kAlertTipOfInternetFailure];
                              }
                          }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }else{
        return 2;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        ECMineSafeTopStyleCell *cell=[ECMineSafeTopStyleCell tableViewCellWithTableView:tableView];
        [cell setContentWithData:self.dataArray[indexPath.section][indexPath.row] andIndex:indexPath];
        return cell;
    }else{
        ECMineSafeBottomStyleCell *cell = [ECMineSafeBottomStyleCell tableViewCellWithTableView:tableView];
        [cell setContentWithData:self.dataArray[indexPath.section][indexPath.row] andIndex:indexPath];
        
        WeakSelf(weakSelf);
        
        cell.block_btn = ^(NSInteger index) {
            SSDKPlatformType platformType;
            if (([weakSelf.dataArray[1][0][1] intValue] == 1 ) && ([weakSelf.dataArray[1][1][1] intValue] == 1)) {//qq 微信 都绑定情况下
                DLog(@"都绑定情况下");
                platformType = (index == 11) ? SSDKPlatformTypeQQ : SSDKPlatformTypeWechat;
                [self cancelAuthorWith:platformType];//解绑操作
                return;
            }
            if (([weakSelf.dataArray[1][0][1] intValue] == 1 ) || ([weakSelf.dataArray[1][1][1] intValue] == 1)){//qq 微信 只有一个绑定情况下
                DLog(@"只有一个绑定");
                
                if (index == 11) {//qq
                    if ([weakSelf.dataArray[1][0][1] intValue] == 1) {//绑定
                        if ([strOfStyle isEqualToString:@"已设置"]) {
                            [self cancelAuthorWith:SSDKPlatformTypeQQ];
                        }else{
                            [MBProgressHUD showTipMessageInWindow:@"请先设置登录密码,再解绑"];
                        }
                    }else{
                        [self allowAutohrWith:SSDKPlatformTypeQQ];
                    }
                }else{//微信
                    if ([weakSelf.dataArray[1][1][1] intValue] == 1) {//绑定
                        if ([strOfStyle isEqualToString:@"已设置"]) {
                            [self cancelAuthorWith:SSDKPlatformTypeWechat];
                        }else{
                            [MBProgressHUD showTipMessageInWindow:@"请先设置登录密码,再解绑"];
                        }
                    }else{
                        [self allowAutohrWith:SSDKPlatformTypeWechat];
                    }
                }
                return;
            }
            //以下情况下  是都没有绑定的情况
            platformType = (index == 11) ? SSDKPlatformTypeQQ : SSDKPlatformTypeWechat;
            [self allowAutohrWith:platformType];
        };
        return cell;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *baseview =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kProportion_Height(108))];
    [tableView.tableHeaderView addSubview:baseview];
    baseview.backgroundColor = [UIColor colorWithHexString:@"#F5F5F5"];
    [self.view updateConstraintsIfNeeded];
    
    UILabel *lab = [[UILabel alloc]init];
    [baseview addSubview:lab];
    lab.textColor = [UIColor colorWithHexString:@"#808080"];
    if (section == 0) {
        lab.text = @"基本设置";
    }else{
        lab.text = @"第三方绑定";
    }
    
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(baseview.mas_centerY);
        make.left.equalTo(baseview.mas_left).offset(kProportion_Width(45));
        make.width.equalTo(@150);
        make.height.equalTo(@18);
    }];
    
    return baseview;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:{//修改用户名
                ECMineSafeChangeNameVc *vc = [[ECMineSafeChangeNameVc alloc]init];
                vc.nickName = self.dataArray[indexPath.section][indexPath.row][1];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 1:{
                //根据是否有无电话号码 进入不同界面(修改手机号页面 或者 绑定手机号页面)
                NSString *str = self.dataArray[indexPath.section][indexPath.row][1];
                if ([str isEqualToString:@""]) {//跳转绑定手机号界面
                    ECMineSafeChangeOrBindTelVc *vc = [[ECMineSafeChangeOrBindTelVc alloc]init];
                    vc.vcType = vcTypeFromBindTel;
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    ECMineSafeCheckPsVc *vc = [[ECMineSafeCheckPsVc alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
                break;
            case 2:{//邮箱验证
                
            }
                break;
            case 3:{//修改登录密码
                NSString *str = self.dataArray[indexPath.section][indexPath.row][1];
                if ([str isEqualToString:@"未设置"]) {//未设置状态下,进入设置密码界面
                    ECMineSafeFirstSetPasswordVc *vc = [[ECMineSafeFirstSetPasswordVc alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{//已设置状态下,进入重置密码界面
                    ECMineSafeChangePasswordVc *vc = [[ECMineSafeChangePasswordVc alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
                break;
            default:
                break;
        }
    }else{//session == 1
        
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kProportion_Height(108);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return kProportion_Height(144);
    }else{
        return kProportion_Height(180);
    }
}

-(UITableView *)safeTBview{
    if (!_safeTBview) {
        _safeTBview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _safeTBview.backgroundColor = [UIColor whiteColor];
        _safeTBview.delegate = self;
        _safeTBview.dataSource = self;
        _safeTBview.separatorStyle = 0;
    }
    return _safeTBview;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
        
        NSMutableArray *arr00 = [[NSMutableArray alloc]initWithArray:@[@"用户名",@""]];
        NSMutableArray *arr01 = [[NSMutableArray alloc]initWithArray:@[@"手机绑定",@""]];
        NSMutableArray *arr02 = [[NSMutableArray alloc]initWithArray:@[@"邮箱验证",@""]];
        NSMutableArray *arr03 = [[NSMutableArray alloc]initWithArray:@[@"登录密码",@""]];

        NSMutableArray *arr10 = [[NSMutableArray alloc]initWithArray:@[@"QQ",@""]];
        NSMutableArray *arr11 = [[NSMutableArray alloc]initWithArray:@[@"Wechat",@""]];
        
        _dataArray = [[NSMutableArray alloc]initWithArray:@[@[arr00,arr01,arr02,arr03],@[arr10,arr11]]];
    }
    return _dataArray;
}

/**
 允许授权操作
 */
-(void)allowAutohrWith:(SSDKPlatformType)platformType{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    //此方法 会每次都调取第三方客户端(注释此方法,第三方客户端只有在首次授权之后才会调出,一旦授权 不会再出现第三方客户端界面)
    [ShareSDK authorize:platformType
               settings:nil
         onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
         }];
    
    [ShareSDK getUserInfo:platformType
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error){
               if (platformType == SSDKPlatformTypeQQ) {
                   SSDKCredential *dict = user.credential;
                   NSString *ulr = [NSString stringWithFormat:@"https://graph.qq.com/oauth2.0/me?access_token=%@&unionid=1",dict.token];
                   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
                   manager.responseSerializer = [AFHTTPResponseSerializer serializer];
                   [manager GET:ulr
                     parameters:nil
                       progress:^(NSProgress * _Nonnull downloadProgress) {}
                        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            NSLog(@"这里打印请求成功要做的事");
                            NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                            
                            NSLog(@"str = %@",string);
                            if ([string containsString:@"100016"]) {
                                [MBProgressHUD showTipMessageInWindow:@"用户凭证已过期,请重新获取"];
                                return;
                            }
                            NSRange startRange = [string rangeOfString:@"UID_"];
                            NSRange endRange = [string rangeOfString:@"""} );"];
                            NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length-1);
                            NSString *result = [string substringWithRange:range];
                            DLog(@"%@",result);
                            
                            [self otherWithPlatformType:SSDKPlatformTypeQQ andStatus:state andUnionID:result];
                            
                        }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
                            NSLog(@"%@",error);  //这里打印错误信息
                        }];
               }else{
                   [self otherWithPlatformType:SSDKPlatformTypeWechat andStatus:state andUnionID:[(NSDictionary *)user.rawData objectForKey:@"unionid"]];
               }
     }];
}

-(void)otherWithPlatformType:(SSDKPlatformType)platformType andStatus:(SSDKResponseState)state andUnionID:(NSString *)unionid{
    if (state == SSDKResponseStateSuccess){
        NSString *type = [[NSString alloc]init];
        if (platformType == SSDKPlatformTypeQQ) {
            type = @"qq";
        }else{
            type = @"weixinweb";
        }
        [HWHttpTool requestWithMethod:@"POST"
                                  url:URL_POST_SettingBind
                               params:@{
                                        @"id":unionid,
                                        @"type":type,
                                        }
                              headers:@{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                              success:^(id json) {
                                  [MBProgressHUD hideHUDForView:self.view animated:YES];
                                  if ([json[@"code"]intValue] == 200) {
                                      [MBProgressHUD showTipMessageInWindow:@"绑定成功"];
                                      
                                      NSInteger row;
                                      if (platformType == SSDKPlatformTypeQQ) {
                                          row = 0;
                                          //最后绑定返回标志是:true or false  采用字典形式
                                          [self.dataArray[1][0] replaceObjectAtIndex:1 withObject:@"1"];//QQ绑定
                                      }else{
                                          row = 1;
                                          [self.dataArray[1][1] replaceObjectAtIndex:1 withObject:@"1"];//微信绑定
                                      }
                                      NSIndexPath *indexPath=[NSIndexPath indexPathForRow:row inSection:1];
                                      
                                      [self.safeTBview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                                      
                                  }else{
                                      [MBProgressHUD showTipMessageInWindow:json[@"message"]];
                                  }
                              }failure:^(NSError *error) {
                                  
                                  NSString *str = [ECData_Json requestErrorTipWith:error];
                                  DLog(@"%@",str);
                                  if (!([str isEqualToString:@"101"] || [str isEqualToString:@"401"])) {
                                      [MBProgressHUD showTipMessageInWindow:kAlertTipOfInternetFailure];
                                  }
                                  [MBProgressHUD hideHUDForView:self.view animated:YES];
                                  [MBProgressHUD showTipMessageInWindow:@"网络连接失败,请重试"];
                              }];
    }else{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showTipMessageInWindow:@"验证失败,请重试"];
    }
}




/**
 取消授权操作
 */
-(void)cancelAuthorWith:(SSDKPlatformType)platformType{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *type = [[NSString alloc]init];
    if (platformType == SSDKPlatformTypeQQ) {
        type = @"qq";
    }else{
        type = @"weixinweb";
    }
    [HWHttpTool requestWithMethod:@"POST"
                              url:URL_POST_Unbind
                           params:@{
                                    @"type":type
                                    }
                          headers:@{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              if ([json[@"code"]intValue] == 200) {
                                  [ShareSDK cancelAuthorize:platformType];
                                  
                                  DLog(@"%d",[ShareSDK hasAuthorized:platformType]);
                                  
                                  [MBProgressHUD showTipMessageInWindow:@"解绑成功"];
                                  NSInteger row = 10;
                                  if (platformType == SSDKPlatformTypeQQ) {
                                      row = 0;
                                      //最后绑定返回标志是:true or false  采用字典形式
                                      [self.dataArray[1][0] replaceObjectAtIndex:1 withObject:@"0"];//QQ解绑
                                  }else{
                                      row = 1;
                                      [self.dataArray[1][1] replaceObjectAtIndex:1 withObject:@"0"];//微信解绑
                                  }
                                  NSIndexPath *indexPath=[NSIndexPath indexPathForRow:row inSection:1];
                                  
                                  [self.safeTBview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                              }else{
                                  [MBProgressHUD showTipMessageInWindow:@"绑定失败,请重试"];
                              }
                          }
                          failure:^(NSError *error) {
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                          }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
